package com.kaifamiao.form;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@WebServlet( "/sign/up" )
public class SignUpServlet extends HttpServlet {

    @Override
    protected void service( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        // 设置请求的编码
        request.setCharacterEncoding( "UTF-8" );
        // 设置响应的编码
        response.setCharacterEncoding( "UTF-8" );

        // 设置 content-type
        response.setContentType( "text/html");

        PrintWriter out = response.getWriter();

        // 根据表单控件名称(表单组件的name属性取值)获取相应的值
        String email = request.getParameter( "email" );
        if( Objects.isNull( email ) || email.trim().isEmpty() ) {
            out.println( "<p style='color: red;'>邮箱不可以为空</p>" );
            return ;
        }

        String password = request.getParameter( "password" );
        if( Objects.isNull( password ) || password.trim().isEmpty() ) {
            out.println( "<p  style='color: red;'>密码不可以为空</p>" );
            return ;
        }

        String confirm = request.getParameter( "confirm" );

        if( !password.trim().equals( confirm )){
            out.println( "<p  style='color: red;'>两次密码不一致</p>" );
            return ;
        }

        // 先执行查询操作获得数据库中主键的最大值
        // MySQL: SELECT max( ifnull( id , 0 ) ) FROM t_customers
        // Oracle: SELECT max( nvl( id , 0 ) ) FROM t_customers
        // 获取到最大值之后加上 1 就是即将保存的数据的 主键值

        // 此时可以将 email 和 password 保存到数据库中
        System.out.println( email + " , " + password );

        // 如果要对密码进行加密应该如何处理(选做)

        out.println( "<p style='color:green;'>注册成功</p>");

        out.println( "<a href='/customer/list'>用户列表</p>");

    }

}
